<template>
  <div class="topics-container">
    <!-- 搜索表单 -->
    <div class="mb10">
      <SearchForm :searchFields="searchItems" :maxFirstRowItems="3" @search="handleSearch" @reset="handleReset" />
    </div>

    <!-- 操作按钮 -->
    <div class="mb10">
      <div class="table-operations">
        <a-button type="primary" danger :disabled="!hasSelected" @click="handleBatchDelete">
          <DeleteOutlined /> 批量删除
        </a-button>
        <span style="margin-left: 8px;" v-if="hasSelected">
          已选择 {{ selectedRowKeys.length }} 项
        </span>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="card-wrap">
      <DataList ref="dataListRef" :api="topicApi.getTopics" :deleteApi="topicApi.deleteTopic" :columns="columns"
        :rowSelection="rowSelection" @action="onAction">
        <!-- 自定义列插槽 -->
        <template #name="{ record }">
          <div class="topic-name">
            <div class="name-text">{{ record.name }}</div>
            <div class="topic-meta">
              <span class="meta-item">成员: {{ record.user_num }}</span>
              <span class="meta-item">帖子: {{ record.post_num }}</span>
            </div>
          </div>
        </template>

        <template #cover_image="{ record }">
          <div class="topic-cover">
            <a-image v-if="record.cover_image" :src="getImageUrl(record.cover_image)" :width="80" :height="60"
              :preview="true" style="border-radius: 4px; object-fit: cover;" />
            <div v-else class="no-cover">
              <span>无封面</span>
            </div>
          </div>
        </template>

        <template #description="{ record }">
          <div class="topic-description">
            {{ record.description ? record.description.substring(0, 80) + (record.description.length > 80 ? '...' : '')
              : '无描述' }}
          </div>
        </template>

        <template #user="{ record }">
          <div class="user-info">
            <a-avatar :src="getImageUrl(record.user?.avatar)" size="small">
              {{ record.user?.nickname?.charAt(0) }}
            </a-avatar>
            <div class="user-details">
              <div>{{ record.user?.nickname || '未知用户' }}</div>
            </div>
          </div>
        </template>

        <template #status="{ record }">
          <a-tag v-if="record.status === 0" color="red">关闭</a-tag>
          <a-tag v-else-if="record.status === 1" color="green">正常</a-tag>
          <a-tag v-else-if="record.status === 2" color="gold">推荐</a-tag>
        </template>

        <template #created_at="{ record }">
          <div>{{ formatDate(record.created_at) }}</div>
        </template>

        <template #action="{ record }">
          <a-space>
            <a-button type="link" size="small" @click="viewDetail(record)">
              查看详情
            </a-button>
            <a-button type="link" size="small" @click="editTopic(record)">
              编辑
            </a-button>
            <a-dropdown>
              <a-button type="link" size="small">
                更多
                <DownOutlined />
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="recommend" @click="handleStatusChange(record, 2)">
                    <StarOutlined /> 设为推荐
                  </a-menu-item>
                  <a-menu-item key="normal" @click="handleStatusChange(record, 1)">
                    <CheckOutlined /> 设为正常
                  </a-menu-item>
                  <a-menu-item key="close" @click="handleStatusChange(record, 0)">
                    <StopOutlined /> 关闭圈子
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="delete" danger>
                    <a-popconfirm title="确定要删除这个圈子吗？" @confirm="handleDelete(record.id)">
                      <DeleteOutlined /> 删除圈子
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-space>
        </template>
      </DataList>
    </div>

    <!-- 圈子详情模态框 -->
    <a-modal v-model:open="detailModalVisible" title="圈子详情" width="800px" :footer="null">
      <div v-if="currentTopic" class="topic-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="圈子名称" :span="2">
            {{ currentTopic.name }}
          </a-descriptions-item>
          <a-descriptions-item label="圈子描述" :span="2">
            <div class="topic-description-detail">{{ currentTopic.description || '无描述' }}</div>
          </a-descriptions-item>
          <a-descriptions-item label="创建者">
            {{ currentTopic.user?.nickname || '未知用户' }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag v-if="currentTopic.status === 0" color="red">关闭</a-tag>
            <a-tag v-else-if="currentTopic.status === 1" color="green">正常</a-tag>
            <a-tag v-else-if="currentTopic.status === 2" color="gold">推荐</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="成员数量">
            {{ currentTopic.user_num }}
          </a-descriptions-item>
          <a-descriptions-item label="帖子数量">
            {{ currentTopic.post_num }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDate(currentTopic.created_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatDate(currentTopic.updated_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="公告" :span="2">
            <div class="topic-notice">{{ currentTopic.notice || '无公告' }}</div>
          </a-descriptions-item>
        </a-descriptions>

        <!-- 封面图片展示 -->
        <div v-if="currentTopic.cover_image" class="cover-section" style="margin-top: 16px;">
          <h4>封面图片</h4>
          <img :src="getImageUrl(currentTopic.cover_image)" alt="封面"
            style="max-width: 300px; max-height: 200px; border-radius: 4px;" />
        </div>

        <!-- 背景图片展示 -->
        <div v-if="currentTopic.bg_image" class="bg-section" style="margin-top: 16px;">
          <h4>背景图片</h4>
          <img :src="getImageUrl(currentTopic.bg_image)" alt="背景"
            style="max-width: 300px; max-height: 200px; border-radius: 4px;" />
        </div>
      </div>
    </a-modal>

    <!-- 编辑圈子模态框 -->
    <a-modal v-model:open="editModalVisible" title="编辑圈子" width="600px" @ok="handleSave" :confirmLoading="saveLoading">
      <a-form ref="formRef" :model="editForm" :rules="editRules" layout="vertical">
        <a-form-item label="圈子名称" name="name">
          <a-input v-model:value="editForm.name" placeholder="请输入圈子名称" />
        </a-form-item>
        <a-form-item label="圈子描述" name="description">
          <a-textarea v-model:value="editForm.description" placeholder="请输入圈子描述" :rows="3" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="editForm.status" placeholder="请选择状态">
            <a-select-option :value="0">关闭</a-select-option>
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="2">推荐</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="公告" name="notice">
          <a-textarea v-model:value="editForm.notice" placeholder="请输入圈子公告" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { DeleteOutlined, DownOutlined, StarOutlined, CheckOutlined, StopOutlined } from '@ant-design/icons-vue'
import DataList from '@/components/DataList.vue'
import SearchForm from '@/components/SearchForm.vue'
import { topicApi } from '@/api/content'
import { formatDate } from '@/utils/date'
import { getImageUrl } from '@/utils/utils'

// 响应式数据
const dataListRef = ref()
const formRef = ref()
const selectedRowKeys = ref([])
const detailModalVisible = ref(false)
const editModalVisible = ref(false)
const saveLoading = ref(false)
const currentTopic = ref(null)
const classOptions = ref([])
const statistics = reactive({
  total_topics: 0,
  active_topics: 0,
  recommended_topics: 0,
  today_topics: 0
})

// 编辑表单
const editForm = reactive({
  id: null,
  name: '',
  description: '',
  status: 1,
  notice: ''
})

// 表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入圈子名称', trigger: 'blur' },
    { max: 20, message: '圈子名称不能超过20个字符', trigger: 'blur' }
  ],
  description: [
    { max: 255, message: '圈子描述不能超过255个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  notice: [
    { max: 1000, message: '公告不能超过1000个字符', trigger: 'blur' }
  ]
}

// 搜索表单配置
const searchItems = ref([
  {
    label: '圈子名称',
    prop: 'name',
    type: 'input',
    placeholder: '请输入圈子名称'
  },
  {
    label: '描述',
    prop: 'description',
    type: 'input',
    placeholder: '请输入圈子描述关键词'
  },
  {
    label: '创建者ID',
    prop: 'user_id',
    type: 'input',
    placeholder: '请输入创建者ID'
  },
  {
    label: '状态',
    prop: 'status',
    type: 'select',
    placeholder: '请选择状态',
    options: [
      { label: '关闭', value: 0 },
      { label: '正常', value: 1 },
      { label: '推荐', value: 2 }
    ]
  },
  {
    label: '分类',
    prop: 'class_id',
    type: 'select',
    placeholder: '请选择分类',
    options: classOptions,
    showSearch: true
  },
  {
    label: '创建时间',
    prop: 'date_range',
    type: 'daterange',
    placeholder: ['开始日期', '结束日期']
  }
])

// 表格列配置
const columns = [
  {
    title: '封面',
    dataIndex: 'cover_image',
    width: 120,
    slot: true
  },
  {
    title: '圈子名称',
    dataIndex: 'name',
    width: 200,
    slot: true
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: 250,
    slot: true
  },
  {
    title: '创建者',
    dataIndex: 'user',
    width: 150,
    slot: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 120,
    slot: true
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    width: 180,
    slot: true,
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    type: 'action',
    options: [
      { title: '查看', key: 'view' },
      { title: '编辑', key: 'edit' },
      { title: '删除', key: 'delete', type: 'delete' }
    ]
  }
]

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}

// 计算属性
const hasSelected = computed(() => selectedRowKeys.value.length > 0)

// 方法
const onAction = (item, record) => {
  if (item.key === 'view') {
    viewDetail(record)
  } else if (item.key === 'edit') {
    editTopic(record)
  }
}

const handleSearch = (params) => {
  // 处理日期范围
  if (params.date_range && params.date_range.length === 2) {
    params.start_date = params.date_range[0]
    params.end_date = params.date_range[1]
    delete params.date_range
  }

  dataListRef.value.search(params)
}

const handleReset = () => {
  dataListRef.value.reset()
}

const handleDelete = async (id) => {
  try {
    await topicApi.deleteTopic({ id })
    message.success('删除成功')
    dataListRef.value.refreshData()
  } catch (error) {
    message.error('删除失败：' + error.message)
  }
}

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的圈子')
    return
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个圈子吗？`,
    onOk: async () => {
      try {
        await topicApi.batchDeleteTopics({ ids: selectedRowKeys.value })
        message.success('批量删除成功')
        selectedRowKeys.value = []
        dataListRef.value.refreshData()
      } catch (error) {
        message.error('批量删除失败：' + error.message)
      }
    }
  })
}

const handleStatusChange = async (record, status) => {
  record.statusLoading = true
  try {
    await topicApi.updateTopicStatus({ id: record.id, status })
    record.status = status
    const statusText = { 0: '关闭', 1: '正常', 2: '推荐' }
    message.success(`圈子状态已更新为：${statusText[status]}`)
    dataListRef.value.refreshData()
  } catch (error) {
    message.error('状态更新失败：' + error.message)
  } finally {
    record.statusLoading = false
  }
}

const viewDetail = async (record) => {
  try {
    console.log('查看详情，圈子ID:', record.id)
    const response = await topicApi.getTopicDetail({ id: record.id })
    console.log('API响应:', response)

    if (response && response.result) {
      currentTopic.value = response.result
      detailModalVisible.value = true
      console.log('设置圈子详情:', currentTopic.value)
    } else {
      message.error('获取圈子详情失败：响应数据为空')
    }
  } catch (error) {
    console.error('获取圈子详情错误:', error)
    message.error('获取圈子详情失败：' + error.message)
  }
}

const editTopic = (record) => {
  editForm.id = record.id
  editForm.name = record.name
  editForm.description = record.description || ''
  editForm.status = record.status
  editForm.notice = record.notice || ''
  editModalVisible.value = true
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    saveLoading.value = true

    await topicApi.saveTopic(editForm)
    message.success('保存成功')
    editModalVisible.value = false
    dataListRef.value.refreshData()
  } catch (error) {
    if (error.message) {
      message.error('保存失败：' + error.message)
    }
  } finally {
    saveLoading.value = false
  }
}

const loadClassOptions = async () => {
  try {
    const response = await topicApi.getTopicClassOptions()
    classOptions.value = response.data.map(item => ({
      label: item.name,
      value: item.id
    }))
  } catch (error) {
    console.error('获取分类选项失败：', error)
  }
}



// 生命周期
onMounted(() => {
  loadClassOptions()
})
</script>

<style scoped>
.topics-container {
  padding: 24px;
}

.topic-name {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.name-text {
  font-weight: 500;
  color: #1890ff;
  cursor: pointer;
}

.topic-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #666;
}

.meta-item {
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.topic-description {
  color: #666;
  line-height: 1.4;
  max-width: 250px;
  word-break: break-all;
}

.topic-cover {
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-cover {
  width: 80px;
  height: 60px;
  background: #f5f5f5;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-id {
  font-size: 12px;
  color: #999;
}

.topic-description-detail {
  max-height: 150px;
  overflow-y: auto;
  line-height: 1.6;
  white-space: pre-wrap;
}

.topic-notice {
  max-height: 100px;
  overflow-y: auto;
  line-height: 1.6;
  white-space: pre-wrap;
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
}

.cover-section,
.bg-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.statistics-cards .ant-card {
  text-align: center;
}

.table-operations {
  display: flex;
  align-items: center;
}
</style>